package com.lzb.compressmaster.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.pdf.PdfDocument;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.PathUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImageToPdfUtils {
    
    private static final String TAG = "ImageToPdfUtils";
    
    /**
     * PDF转换配置类
     */
    public static class PdfConfig {
        public int pageWidth = 595;      // 页面宽度 (A4: 595pt)
        public int pageHeight = 842;     // 页面高度 (A4: 842pt)
        public int margin = 40;          // 页边距
        public int quality = 100;        // 图片质量 (1-100)
        public boolean autoRotate = true;  // 是否自动旋转适应页面
        public boolean centerImage = true; // 是否居中显示图片
        public float compressionRatio = 1.0f; // 压缩比例 (1.0 = 不压缩)
        public boolean fitToPage = true;   // 是否适应页面大小
        public boolean maintainAspectRatio = true; // 是否保持宽高比

        public PdfConfig() {
        }

        public PdfConfig(int pageWidth, int pageHeight, int margin) {
            this.pageWidth = pageWidth;
            this.pageHeight = pageHeight;
            this.margin = margin;
        }
    }
    
    /**
     * 图片转PDF的转换结果类
     */
    public static class ConversionResult {
        public boolean success;
        public String outputPath;
        public int pageCount;
        public long fileSize;
        public String errorMessage;

        public ConversionResult(boolean success, String outputPath, int pageCount, long fileSize) {
            this.success = success;
            this.outputPath = outputPath;
            this.pageCount = pageCount;
            this.fileSize = fileSize;
            this.errorMessage = "";
        }

        public ConversionResult(String errorMessage) {
            this.success = false;
            this.errorMessage = errorMessage;
        }
    }
    
    /**
     * 转换进度监听回调接口
     */
    public interface OnConversionListener {
        void onConversionStart(int totalImages);
        void onImageProcessed(int currentIndex, int totalImages, String imagePath);
        void onConversionComplete(ConversionResult result);
        void onConversionError(String errorMessage);
    }
    
    /**
     * 将图片列表转换为PDF（带监听回调）
     *
     * @param context    上下文
     * @param imagePaths 图片路径列表
     * @param listener   转换进度监听
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static void convertImagesToPdf(Context context, List<String> imagePaths, OnConversionListener listener) {
        convertImagesToPdf(context, imagePaths, new PdfConfig(), listener);
    }
    
    /**
     * 将图片列表转换为PDF（带配置参数和监听回调）
     *
     * @param context    上下文
     * @param imagePaths 图片路径列表
     * @param config     PDF配置
     * @param listener   转换进度监听
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static void convertImagesToPdf(Context context, List<String> imagePaths, PdfConfig config, OnConversionListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("OnConversionListener cannot be null");
        }
        
        if (imagePaths == null || imagePaths.isEmpty()) {
            listener.onConversionError("图片列表为空");
            return;
        }
        
        String fileName = "Tmp_" + System.currentTimeMillis();
        String outputPath = PathUtils.getFilesPathExternalFirst() + "/work/pdf/" + fileName + ".pdf";
        if (outputPath == null || outputPath.trim().isEmpty()) {
            listener.onConversionError("输出路径无效");
            return;
        }
        
        // 确保输出目录存在
        File outputFile = new File(outputPath);
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }
        
        // 过滤有效图片
        List<String> validImagePaths = new ArrayList<>();
        for (String imagePath : imagePaths) {
            if (isValidImage(imagePath)) {
                validImagePaths.add(imagePath);
            }
        }
        
        if (validImagePaths.isEmpty()) {
            listener.onConversionError("没有有效的图片可以转换");
            return;
        }
        
        // 通知开始转换
        listener.onConversionStart(validImagePaths.size());
        
        // 在后台线程中执行转换
        new Thread(() -> {
            PdfDocument document = new PdfDocument();
            int validPageCount = 0;
            
            try {
                for (int i = 0; i < validImagePaths.size(); i++) {
                    String imagePath = validImagePaths.get(i);
                    
                    // 通知当前处理进度
                    listener.onImageProcessed(i + 1, validImagePaths.size(), imagePath);
                    
                    Bitmap bitmap = loadAndProcessBitmap(imagePath, config);
                    if (bitmap == null) {
                        Log.w(TAG, "无法加载图片: " + imagePath);
                        continue;
                    }
                    
                    // 创建页面
                    PdfDocument.PageInfo pageInfo = createPageInfo(bitmap, config);
                    PdfDocument.Page page = document.startPage(pageInfo);
                    
                    // 在页面上绘制图片
                    drawImageOnPage(page.getCanvas(), bitmap, config, pageInfo.getPageWidth(), pageInfo.getPageHeight());
                    
                    document.finishPage(page);
                    validPageCount++;
                    
                    // 回收bitmap内存
                    if (!bitmap.isRecycled()) {
                        bitmap.recycle();
                    }
                }
                
                if (validPageCount == 0) {
                    document.close();
                    listener.onConversionError("没有有效的图片可以转换");
                    return;
                }
                
                // 保存PDF文件
                try (FileOutputStream fos = new FileOutputStream(outputFile)) {
                    document.writeTo(fos);
                }
                
                long fileSize = outputFile.length();
                document.close();
                
                ConversionResult result = new ConversionResult(true, outputPath, validPageCount, fileSize);
                listener.onConversionComplete(result);
                
            } catch (Exception e) {
                Log.e(TAG, "转换PDF失败", e);
                document.close();
                listener.onConversionError("转换失败: " + e.getMessage());
            }
        }).start();
    }
    
    /**
     * 加载并处理图片
     */
    private static Bitmap loadAndProcessBitmap(String imagePath, PdfConfig config) {
        try {
            // 获取图片原始尺寸
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imagePath, options);

            if (options.outWidth <= 0 || options.outHeight <= 0) {
                return null;
            }

            // 计算采样率以避免内存溢出
            int sampleSize = calculateSampleSize(options, config);

            // 加载实际图片
            options.inJustDecodeBounds = false;
            options.inSampleSize = sampleSize;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;

            Bitmap originalBitmap = BitmapFactory.decodeFile(imagePath, options);
            if (originalBitmap == null) {
                return null;
            }

            // 应用压缩
            if (config.compressionRatio < 1.0f) {
                int newWidth = (int) (originalBitmap.getWidth() * config.compressionRatio);
                int newHeight = (int) (originalBitmap.getHeight() * config.compressionRatio);

                Bitmap compressedBitmap = Bitmap.createScaledBitmap(
                        originalBitmap, newWidth, newHeight, true);

                if (compressedBitmap != originalBitmap) {
                    originalBitmap.recycle();
                }

                return compressedBitmap;
            }

            return originalBitmap;

        } catch (Exception e) {
            Log.e(TAG, "加载图片失败: " + imagePath, e);
            return null;
        }
    }

    /**
     * 计算图片采样率
     */
    private static int calculateSampleSize(BitmapFactory.Options options, PdfConfig config) {
        final int height = options.outHeight;
        final int width = options.outWidth;

        int sampleSize = 1;

        // 计算最大允许尺寸
        int maxWidth = config.pageWidth - 2 * config.margin;
        int maxHeight = config.pageHeight - 2 * config.margin;

        if (config.autoRotate && width > height && maxHeight > maxWidth) {
            // 如果图片横向且页面纵向，交换最大尺寸
            int temp = maxWidth;
            maxWidth = maxHeight;
            maxHeight = temp;
        }

        if (height > maxHeight || width > maxWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            while ((halfHeight / sampleSize) >= maxHeight &&
                    (halfWidth / sampleSize) >= maxWidth) {
                sampleSize *= 2;
            }
        }

        return sampleSize;
    }

    /**
     * 创建PDF页面信息
     */
    private static PdfDocument.PageInfo createPageInfo(Bitmap bitmap, PdfConfig config) {
        int pageWidth = config.pageWidth;
        int pageHeight = config.pageHeight;

        // 根据图片方向决定是否旋转页面
        if (config.autoRotate && bitmap.getWidth() > bitmap.getHeight() && pageWidth < pageHeight) {
            // 横向图片，使用横向页面
            return new PdfDocument.PageInfo.Builder(pageHeight, pageWidth, 1).create();
        }

        return new PdfDocument.PageInfo.Builder(pageWidth, pageHeight, 1).create();
    }

    /**
     * 在PDF页面上绘制图片
     */
    private static void drawImageOnPage(Canvas canvas, Bitmap bitmap, PdfConfig config, int pageWidth, int pageHeight) {
        // 计算绘制区域
        int availableWidth = pageWidth - 2 * config.margin;
        int availableHeight = pageHeight - 2 * config.margin;

        float imageAspect = (float) bitmap.getWidth() / bitmap.getHeight();
        float availableAspect = (float) availableWidth / availableHeight;

        int drawWidth, drawHeight;

        if (config.fitToPage) {
            if (config.maintainAspectRatio) {
                // 保持宽高比适应页面
                if (imageAspect > availableAspect) {
                    // 图片更宽，按宽度缩放
                    drawWidth = availableWidth;
                    drawHeight = (int) (availableWidth / imageAspect);
                } else {
                    // 图片更高，按高度缩放
                    drawHeight = availableHeight;
                    drawWidth = (int) (availableHeight * imageAspect);
                }
            } else {
                // 拉伸填满
                drawWidth = availableWidth;
                drawHeight = availableHeight;
            }
        } else {
            // 使用原始尺寸
            drawWidth = Math.min(bitmap.getWidth(), availableWidth);
            drawHeight = Math.min(bitmap.getHeight(), availableHeight);
        }

        // 计算绘制位置
        int drawX, drawY;
        if (config.centerImage) {
            drawX = (pageWidth - drawWidth) / 2;
            drawY = (pageHeight - drawHeight) / 2;
        } else {
            drawX = config.margin;
            drawY = config.margin;
        }

        // 创建绘制区域
        Rect destRect = new Rect(drawX, drawY, drawX + drawWidth, drawY + drawHeight);

        // 绘制白色背景
        Paint backgroundPaint = new Paint();
        backgroundPaint.setColor(Color.WHITE);
        canvas.drawRect(0, 0, pageWidth, pageHeight, backgroundPaint);

        // 绘制图片
        Paint imagePaint = new Paint();
        imagePaint.setFilterBitmap(true);
        imagePaint.setDither(true);

        canvas.drawBitmap(bitmap, null, destRect, imagePaint);
    }

    /**
     * 检查图片是否有效
     */
    public static boolean isValidImage(String imagePath) {
        if (imagePath == null || imagePath.trim().isEmpty()) {
            return false;
        }

        File file = new File(imagePath);
        if (!file.exists() || !file.canRead()) {
            return false;
        }

        String extension = imagePath.substring(imagePath.lastIndexOf(".") + 1).toLowerCase();
        return extension.matches("(jpg|jpeg|png|bmp|webp)");
    }

    /**
     * 获取PDF文件信息
     */
    public static String getPdfInfo(String pdfPath) {
        File file = new File(pdfPath);
        if (!file.exists()) {
            return "文件不存在";
        }

        long fileSize = file.length();
        String sizeStr = formatFileSize(fileSize);

        return String.format("文件大小: %s\n最后修改: %s\n页数: %d",
                sizeStr,
                new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
                        .format(new java.util.Date(file.lastModified())),
                1); // 简单实现，实际应该读取PDF页数
    }

    /**
     * 格式化文件大小
     */
    public static String formatFileSize(long size) {
        if (size <= 0) return "0 B";

        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));

        return new java.text.DecimalFormat("#,##0.#").format(
                size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    /**
     * 批量检查图片有效性
     */
    public static int countValidImages(List<String> imagePaths) {
        if (imagePaths == null) return 0;

        int count = 0;
        for (String path : imagePaths) {
            if (isValidImage(path)) {
                count++;
            }
        }
        return count;
    }
}